package com.ruoyi.experiment.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.experiment.domain.*;
import com.ruoyi.experiment.mapper.ExperimentMapper;
import com.ruoyi.experiment.mapper.ExperimentOutMapper;
import com.ruoyi.experiment.model.*;
import com.ruoyi.experiment.service.IExperimentOutService;
import com.ruoyi.experiment.utils.Num;
import com.ruoyi.sample.mapper.SampleLzMapper;
import com.ruoyi.sample.mapper.SampleMapper;
import com.ruoyi.sample.model.SampleLz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ExperimentOutServiceImpl implements IExperimentOutService {

    @Autowired
    ExperimentOutMapper experimentMapper;
    @Autowired
    ExperimentMapper expeMapper;
    @Autowired
    SampleLzMapper sampleLzMapper;
    @Autowired
    SampleMapper sampleMapper;


    @Override
    public List<EProject> selectAllItem(Project project) {
        return experimentMapper.selectAllItem(project);
    }

    @Override
    public List<Sample> selectSamples(Sample sample) {
        return experimentMapper.selectSamples(sample);
    }


    @Override
    @Transactional
    public boolean flume(ExperimentFlume flume) {
        for (Long id : flume.getIds()) {
            Experiment experiment = experimentMapper.selectExperimentBySampleId(id);
            if (flume.getPostId() == 8) {
                //项目负责人
                if (experiment.getExpermentType()%100/10 >= 3) {
                    continue;
                }
                experimentMapper.flumeExperiment(experiment.getExperimentId(), Num.set(experiment.getExpermentType(), 2, 3));
            }
        }
        Circulation circulation = new Circulation();
        List<Sample> samples = selectSamples(new Sample(flume.getIds().get(0)));
        if (samples == null || samples.isEmpty())
            return false;
        circulation.setCirculationType(flume.getPostId());
        circulation.setProjectId(samples.get(0).getProjectId());
        circulation.setUserName(SecurityUtils.getUsername());
        circulation.setCirculationSuggestion(flume.getCirculationSuggestion());
        experimentMapper.insertFlume(circulation);
        return true;
    }

    /**
     * 查询实验管理
     *
     * @param experimentId 实验管理主键
     * @return 实验管理
     */
    @Override
    public Experiment selectExperimentalManagementByExperimentId(Long experimentId) {
        return experimentMapper.selectExperimentalManagementByExperimentId(experimentId);
    }

    /**
     * 查询实验管理列表
     *
     * @param experimentalManagement 实验管理
     * @return 实验管理
     */
    @Override
    public List<Experiment> selectExperimentalManagementList(Experiment experimentalManagement) {
        return experimentMapper.selectExperimentalManagementList(experimentalManagement);
    }


    /**
     * 分配岗位
     *
     * @param experiment 实验管理
     * @return 结果
     */
    @Override
    public int updateExperimentalManagement(Experiment experiment) {

        experimentMapper.updateProject(experiment.getSampleId());
        Integer status = experiment.getExpermentType();
        if (Num.get(status, 2) < 2) {
            int newStatus = Num.set(status, 2, 2);
            experiment.setExpermentType(newStatus);
        }
        //由管理员分配
        if (experiment.getJobManagerId()!=null){
            experimentMapper.updateExperimentalManagement(experiment);
            confirmLZ(1<<4,experiment.getSampleId());
            return 1;
        }
        Integer jobType = experimentMapper.selectJobTypeByjobId(experiment.getJobId());
        if (jobType==0){
            confirmLZ(1<<4,experiment.getSampleId());
        }
        return experimentMapper.updateExperimentalManagement(experiment);
    }
    private boolean confirmLZ(Integer status, Long id) {
        Sample sample = new Sample();
        sample.setSampleId(id);
        sample.setConfirmStatus(status);
        int i = sampleMapper.updateSample(sample);
        return i==1;
    }

    /**
     * 取消分配岗位
     *
     * @param id
     * @return 结果
     */
    @Override
    public int cancelExperiment(Long id) {
        int count = 0;
        Experiment experiment = experimentMapper.selectExperimentBySampleId(id);
        experiment.setJobId(-1L);
        experiment.setJobPrice(-1L);
        experiment.setJobManagerId(-1L);
        int status = experiment.getExpermentType();
        if (Num.get(status, 2) == 2) {
            int newStatus = Num.set(status, 2, 1);
            experiment.setExpermentType(newStatus);
            experimentMapper.cancelPost(experiment);
            confirmLZ(0, id);
            count++;
        }
        return count;
    }

    @Override
    public List<Job> getAllJob(Integer experimentTypeId) {
        List<Job> jobs = experimentMapper.selectJobByExperimentType(experimentTypeId);
        List<Job> res=new ArrayList<>();
//        Set<Long> manager= new HashSet<>();
        for (Job job : jobs) {
            if (job.getJobType()==0)
                continue;
//                manager.add(128L);//孙一民的id
            else
                res.add(job);
        }
        Job m = new Job();
        m.setManagerId(128L);
        res.add(m);
        return res;
    }


    @Override
    public Experiment getExperimentBySampleId(Long id) {
        return experimentMapper.selectExperimentBySampleId(id);
    }

    @Override
    public List<ESample> listSamplesWithExperiment(Sample sample) {
        return experimentMapper.selectSamplesWithExperiment(sample);
    }

    @Override
    public boolean finishOutExperiment(Long id) {
        Experiment experiment = experimentMapper.selectExperimentalManagementByExperimentId(id);
        int status = experiment.getExpermentType();
        if (status >= 100 && status % 100 >= 30) {
            System.out.println(id);
            System.out.println(experiment.getOrderNum());
            experimentMapper.endOutExperiment(id,experiment.getOrderNum()==0?0:2);
            return true;
        } else
            return false;
    }

    @Override
    public List<TreeSample> getMakeList(Long itemId) {
        List<TreeSample> treeSamples = experimentMapper.selectRootSamples(itemId);
        getTree(treeSamples);
        return treeSamples;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void makeSample(Sample sample) {
        Sample parentSample = expeMapper.selectSampleById(sample.getParentId());
        int i = parentSample.getCurrChildrenId();
        parentSample.setCurrChildrenId(i + 1);
        parentSample.setSampleStatus(6);
        expeMapper.updateSample(parentSample);
        sample.setWellId(parentSample.getWellId());
        sample.setDepth(parentSample.getDepth());
        sample.setProjectId(parentSample.getProjectId());
        sample.setRockType(parentSample.getRockType());
        sample.setSampleStatus(5);
        sample.setSampleName(sample.getSampleName() + "(" + i + ")");
        sample.setConfirmStatus(1<<6);
        experimentMapper.insertSample(sample);
        sampleLzMapper.insertSampleLz(new SampleLz(sample.getSampleId(),"新制备样品", sample.getSampleQuantity(), sample.getSampleSize()));
    }

    @Override
    @Transactional
    public boolean backSample(List<Long> ids) {
        for (Long id : ids) {
            Experiment experiment = experimentMapper.selectExperimentBySampleId(id);
            if (experiment!=null && ( experiment.getExpermentType()%100/10<3 || experiment.getExpermentType()/100<1))
                return false;
            if (experiment!=null && experiment.getExperimentEndDate()==null)
                return false;
        }
        for (Long id : ids) {
            experimentMapper.finishOutExperiment(id);
        }
        for (Long id : ids) {
            experimentMapper.updateMakedSample(id);
            confirmLZ(1<<6,id);
        }
        List<Long> all = new ArrayList<>(ids);
        selectTree(ids, all);
        for (Long ci : all) {
            Sample sample = expeMapper.selectSampleById(ci);
            sampleLzMapper.insertSampleLz(new SampleLz(sample.getSampleId(), "样品退回样品管理员", sample.getSampleQuantity(), sample.getSampleSize()));
        }
        experimentMapper.backSamples(all);
        return true;
    }

    @Override
    public boolean isFinish(Long id) {
        Experiment experiment = experimentMapper.selectExperimentBySampleId(id);
        if (experiment==null || experiment.getExperimentEndDate()==null) {
            return false;
        }
        return true;
    }

    private void selectTree(List<Long> ids, List<Long> res) {
        if (ids == null || ids.size() == 0)
            return;
        List<Long> cids = experimentMapper.selectSampleIdByParentId(ids);
        res.addAll(cids);
        selectTree(cids, res);
    }

    private void getTree(List<TreeSample> treeSamples) {
        if (treeSamples == null || treeSamples.isEmpty())
            return;
        for (TreeSample treeSample : treeSamples) {
            List<TreeSample> children = experimentMapper.selectTreeSamples(treeSample.getSampleId());
            treeSample.setChildren(children);
            getTree(children);
        }
    }

}
